<?php

include("config.php");
if ((!isset($_SESSION["user"]) || $_SESSION["user"] == "") && !isset($_REQUEST["nopdf"])) header('Location: index.php');


$db_www = new DB($server_username,$server_pass,$server_db,$server,$driver);
$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);

if ($db_www->isConnected()) {	
	if (!isset($_REQUEST["nopdf"])) {
		$i_query = str_replace("<kodas>", $_SESSION['user'], $i_query);	
	} else {
		$i_query = str_replace("<kodas>", $_REQUEST['im_kodas'], $ii_query);
	}
	$minfo = $db_www->returnInfo($i_query);	

	$q = "SELECT * FROM n08_klij_c WHERE N08_c_kodas_ks='".addslashes_mssql($minfo["N08_kodas_ks"])."'";
	$rimone = $db_rdata->returnInfo($q);
	if (isset($rimone) && trim($rimone["n08_c_invoice"]) != "") {
		if (file_exists("template/invoice/".trim($rimone["n08_c_invoice"])) ) {
			$tfile = "template/invoice/".trim($rimone["n08_c_invoice"]);
		}
	}

} else {
	die("Klientų aptarnavimo sistema laikinai neveikia.");
}

	if (empty($minfo)) {
		die("Nerasta imone.");
	}

	if (!isset($_REQUEST["dok_nr"])){
		die("Nenurodytas dokumento nr.");
	}

	$oinfo = $db_www->returnInfo($o_query);	
	if (!empty($oinfo)) {
		$o_query = str_replace("<kodas>", $oinfo["N23_REIKSME1"], $ii_query);
		$ourinfo = $db_www->returnInfo($o_query);	
		
		$s_query = str_replace("<kodas>", $oinfo["N23_REIKSME1"], $s_query);
		$saskinfo = $db_www->returnInfo($s_query);
	}
	
	if (isset($_REQUEST["type"]) && $_REQUEST["type"] == "p") {
		if (!isset($_REQUEST["id"])){
			die("Nenurodytas dokumento id.");
		}	else {
			$dok_nr = $_REQUEST["id"];
		}
		$accounts_query2 = str_replace("<im_kodas>", $minfo["N08_kodas_ks"], $accounts_query2);
		$accounts_query2 .= " and I06_KODAS_PO='" . addslashes_mssql($_REQUEST["id"]). "'";		
		$ainfo = $db_www->returnInfo($accounts_query2);	
		//echo $accounts_query2;
		$sask_query2 = str_replace("<dok_nr>", addslashes_mssql($_REQUEST["id"]), $sask_query2);
		$info = $db_www->returnList($sask_query2);	
		//echo $sask_query2;
		$manag_query2 = str_replace("<man_id>", trim(addslashes_mssql($ainfo["I06_KODAS_MS"])), $manag_query2);
		//echo $manag_query2;
		$manager = $db_www->returnInfo($manag_query2);	

		$apmokterm_query = str_replace("<kodas>", $ainfo["I06_KODAS_PO"], $apmokterm_query);
		$tinfo = $db_www->returnInfo($apmokterm_query);	
		if (!empty($tinfo)) {
			if (is_numeric(trim($tinfo["I08_MOK_D"]))){
				$terminas = trim($tinfo["I08_MOK_D"]);
			} else {
				$terminas = "0";
			}
		} else {
			$terminas = "0";
		}
		//echo $apmokterm_query;
		$pastabos_query = str_replace("<kodas>", $ainfo["I06_KODAS_PO"], $pastabos_query);
		$pastinfo = $db_www->returnInfo($pastabos_query);	
		if (!empty($pastinfo)) {		
			$pastabos = iconv('windows-1257', 'UTF-8',$pastinfo["i06_pastabos"]);
		} else {
			$pastabos = "";
		}
		//echo $pastabos_query;
	}	else {
		$dok_nr = $_REQUEST["dok_nr"];
		$sask_query = str_replace("<im_code>", $minfo["N08_kodas_ks"], $sask_query);
		$sask_query = str_replace("<dok_nr>", addslashes_mssql($_REQUEST["dok_nr"]), $sask_query);
		$info = $db_www->returnList($sask_query);
		//echo $sask_query;
		$nuol_query = str_replace("<dok_nr>", addslashes_mssql($_REQUEST["dok_nr"]), $nuol_query);
		$nuol = $db_www->returnInfo($nuol_query);
		//echo $nuol_query;

		
		//echo $sask_query;
		$accounts_query = str_replace("<im_kodas>", $minfo["N08_kodas_ks"], $accounts_query);
		$accounts_query .= " and I32_KLD.I32_DOK_NR='" . addslashes_mssql($_REQUEST["dok_nr"]). "'";
		$accounts_query = str_replace("<suma>", "I32_DEB_SUMA ", $accounts_query);		
		$ainfo = $db_www->returnInfo($accounts_query);	
		//echo $accounts_query;
		$manag_query = str_replace("<dok_nr>", trim(addslashes_mssql($_REQUEST["dok_nr"])), $manag_query);
		//echo $manag_query;
		$manager = $db_www->returnInfo($manag_query);	

		if (is_numeric(trim($minfo["N24_MOK_D"]))){
			$terminas = trim($minfo["N24_MOK_D"]);
		} else {
			$terminas = "0";
		}
		
	}
		
	if (empty($ainfo)){
		die("Neteisingas dokumento nr.");
	}
		logAction("" . $_REQUEST["dok_nr"],7);
		// get esternal file content
		$company = iconv('windows-1257', 'UTF-8',"<br>". $ourinfo["N08_PAV"]);
		$address = iconv('windows-1257', 'UTF-8',"<br>".$ourinfo["N08_ADR"]);
		if ($ourinfo["n09_pav"] != null && trim($ourinfo["n09_pav"])!= "") {
			$address .= ", ". iconv('windows-1257', 'UTF-8',trim($ourinfo["n09_pav"]));
		}
		
		$mcompany = iconv('windows-1257', 'UTF-8',"<br>". $minfo["N08_PAV"]);
		$maddress = iconv('windows-1257', 'UTF-8',"<br>".$minfo["N08_ADR"]);
		if ($minfo["n09_pav"] != null && trim($minfo["n09_pav"])!= "") {
			$maddress .= ", ". iconv('windows-1257', 'UTF-8',trim($minfo["n09_pav"]));
		}		

if (isset($_REQUEST["cred"]) && $_REQUEST["cred"] == "1") {
	$title = "KREDITINĖ PVM SĄSKAITA FAKTŪRA";
} else {
	$title = "PVM Sąskaita Faktūra";
}		
list($width, $height, $type, $attr) = getimagesize("logo.jpg");
if  ($width/$height > 2) {
	$logolimit = "width=\"200\"";
} else {
	$logolimit = "height=\"100\"";
}
	
$header = "<img src=\"logo.jpg\" alt=\"test alt attribute\" ".$logolimit." border=\"0\" /><br>
<table cellspacing=\"0\" cellpadding=\"1\" border=\"0\">
    <tr>
        <td><font size=\"+1\">TIEKĖJAS (PARDAVĖJAS)</font>".
		$company.
	    $address.		
		"<br>
			<table cellspacing=\"0\" cellpadding=\"1\" border=\"0\" width=\"400\">
			<tr>
			<td width=\"120\">Įmonės kodas</td><td>".$ourinfo["N08_IM_KODAS"]."</td>
			</tr>
			<tr>
			<td>PVM kodas</td><td>".$ourinfo["N08_PVM_KODAS"]."</td>
			</tr>
			<tr>
			<td>Banko kodas</td><td>".iconv('windows-1257', 'UTF-8', $saskinfo["N33_KODAS_WS"] . " " . $saskinfo["N34_PAV"])."</td>
			</tr>
			<tr>
			<td>A.s.</td><td>".$saskinfo["N33_S_KODAS"]."</td>
			</tr>		
			</table>		
		</td>
        <td>
		<font size=\"+1\">PIRKĖJAS (MOKĖTOJAS)</font>".
		$mcompany.
	    $maddress.	
		"<br>
			<table cellspacing=\"0\" cellpadding=\"1\" border=\"0\" width=\"400\">
			<tr>
			<td width=\"120\">Įmonės kodas</td><td>".$minfo["N08_IM_KODAS"]."</td>
			</tr>
			<tr>
			<td>PVM kodas</td><td>".$minfo["N08_PVM_KODAS"]."</td>
			</tr>";
		
			$header .= "</table>
		</td>
    </tr>
</table>	
<br><br>
<span style=\"text-align:center;\"><font size=\"+1\"><b>".$title." Serija ".substr($_REQUEST["dok_nr"],0,3)." Nr.".substr($_REQUEST["dok_nr"],3)."</b></font></span>
<br><br>";
if (isset($_REQUEST["type"]) && $_REQUEST["type"] == "p") {
	$opdate = $ainfo["I06_OP_DATA"];
	$paytill = adddays($ainfo["I06_OP_DATA"],$terminas);
	$header .= "<table width=\"1355\">
	<tr><td></td><td width=\"120\">Dokumento data</td><td width=\"80\">".$opdate."</td></tr>
	<tr><td></td><td>Apmokėti iki</td><td>". $paytill ."</td></tr>
	
	</table>";	
	$xx = date_parse_from_format("Y.m.d",$ainfo["I06_OP_DATA"]) ;
} else {

	$opdate = $ainfo["I31_OP_DATA"];
	$paytill = adddays($ainfo["I31_OP_DATA"],$terminas);
	$header .= "<table width=\"1355\">
	<tr><td></td><td width=\"120\">Dokumento data</td><td width=\"80\">".$opdate."</td></tr>
	<tr><td></td><td>Apmokėti iki</td><td>". $paytill ."</td></tr>
	</table>";	
	$xx = date_parse_from_format("Y.m.d",$ainfo["I31_OP_DATA"]) ;
}

$dd = mktime(0,0,0,$xx["month"],$xx["day"],$xx["year"]);

$visobepvm = 0;
$visosupvm = 0;
$pvm_5 = 0;
$pvm_9 = 0;
$pvm_18 = 0;
$pvm_19 = 0;
$pvm_21 = 0;
$html = $header;

	if (isset($_REQUEST["type"]) && $_REQUEST["type"] == "p") {	
	    $html .= "<table width=\"1310\"><tr><td>Pastabos: ".$pastabos."</td></tr></table>";
		if (isset($_REQUEST["cred"]) && $_REQUEST["cred"] == "1") {
			$titkaina = "Kaina";
			$titproc = "PVM tarifas %";
			$titkaina2 = "Suma viso<br>(be PVM)";
			//$delcol = 8;
			$html .= "<table cellspacing=\"0\" cellpadding=\"1\" border = \"0\">				
				<tr style=\"background-color:#EFF9E5;\"><th width=\"70\"><font size=\"-1\">Prekės kodas</font></th><th width=\"205\"><font size=\"-1\">Prekės pavadinimas</font></th><th width=\"40\"><font size=\"-1\">Mato<br>vnt.</font></th><th width=\"80\"><font size=\"-1\">Kiekis</font></th><th width=\"80\"><font size=\"-1\">".$titkaina."</font></th><th width=\"50\" align=\"right\"><font size=\"-1\">".$titproc."</font></th><th align=\"right\"><font size=\"-1\">".$titkaina2."</font></th></tr>
			";	
			
		} else {
			$titkaina = "Kaina<br>(be nuol.)";
			$titproc = "Nuol.<br>%";
			$titkaina2 = "Kaina<br>(po nuol.)";
			//$delcol = 10;
			$html .= "<table cellspacing=\"0\" cellpadding=\"1\" border = \"0\">				
				<tr style=\"background-color:#EFF9E5;\"><th width=\"70\"><font size=\"-1\">Prekės kodas</font></th><th width=\"120\"><font size=\"-1\">Prekės pavadinimas</font></th><th width=\"40\"><font size=\"-1\">Mato<br>vnt.</font></th><th width=\"80\"><font size=\"-1\">Kiekis</font></th><th width=\"60\"><font size=\"-1\">".$titkaina."</font></th><th width=\"50\"><font size=\"-1\">".$titproc."</font></th><th width=\"80\"><font size=\"-1\">".$titkaina2."</font></th><th width=\"50\" align=\"right\"><font size=\"-1\">PVM tarifas %</font></th><th align=\"right\"><font size=\"-1\">Suma viso<br>(be PVM)</font></th></tr>
			";	
		}
	} else {
		$titkaina = "Kaina<br>(be PVM)";
		$titproc = "PVM tarifas %";
		$titkaina2 = "Suma viso<br>(be PVM)";
		//$delcol = 8;
		$html .= "<table cellspacing=\"0\" cellpadding=\"1\" border = \"0\">				
			<tr style=\"background-color:#EFF9E5;\"><th width=\"70\"><font size=\"-1\">Prekės kodas</font></th><th width=\"180\"><font size=\"-1\">Prekės pavadinimas</font></th><th width=\"40\"><font size=\"-1\">Mato<br>vnt.</font></th><th width=\"80\"><font size=\"-1\">Kiekis</font></th><th width=\"110\"><font size=\"-1\">".$titkaina."</font></th><th width=\"50\" align=\"right\"><font size=\"-1\">".$titproc."</font></th><th align=\"right\"><font size=\"-1\">".$titkaina2."</font></th></tr>
		";
	}	
	$skipedsum = "0";
	if (isset($_REQUEST["cred"]) && $_REQUEST["cred"] == "1") {
		$zenklas = -1;
	} else {
		$zenklas = 1;
	}
	$i = 0;
	$duom = array();
	foreach ($info as $line) {
		$i++;
		if (substr(trim($line["I07_PAV"]),0,1)=="!") {
			$skip = true;
			$skipedsum += $line["I07_SUMA"];
		} else {
			$skip = false;
			$visobepvm += $line["I07_SUMA"];
		}
		if (trim($line["I07_TIPAS"])=='4' || trim($line["I07_TIPAS"])=='5') {
			$kodas = "";
			$matas = "";
			$kiekis = "";
			$kainabe = "";
			$nuolaida = "";
			$kainapo = "";
			$suma = "";
			$mokestis = "";
		} else {
			$kodas = iconv('windows-1257', 'UTF-8',trim($line["I07_KODAS"]));
			$matas = iconv('windows-1257', 'UTF-8',trim($line["I07_KODAS_US"]));
			$kiekis = sprintf("%01.3f",$line["i07_kiekis"]);
			$kainabe = sprintf("%01.4f",$line["I07_KAINA_BE"]*$zenklas);
			$nuolaida = $line["i07_nuolaida"];
			$kainapo = sprintf("%01.4f",$line["kaina_po"]*$zenklas);
			$suma = $line["I07_SUMA"];
			$mokestis = $line["I07_MOKESTIS_P"];
		}
	    if ((isset($_REQUEST["type"]) && $_REQUEST["type"] == "p") || !isset($_REQUEST["type"]) && !$skip) {
			$pav = iconv('windows-1257', 'UTF-8',trim(str_replace(chr(160),"",$line["I07_PAV"])));
			$html .= "<tr>";
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$kodas."</font></td>";
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$pav."</font></td>";
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$matas."</font></td>";
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$kiekis."</font></td>";
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$kainabe."</font></td>";
			
			$xsuma = sprintf("%01.2f",$suma*$zenklas); 
			if (isset($_REQUEST["type"]) && $_REQUEST["type"] == "p") {	
				if (isset($_REQUEST["cred"]) && $_REQUEST["cred"] == "1") {
					$nuolaida = $mokestis;
					$kainapo = $xsuma;				
				} else {
					$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$nuolaida."</font></td>";
					$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-1\">".$kainapo."</font></td>";
				}
			} else {
				$nuolaida = $mokestis;
				$kainapo = $xsuma;
			}
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\" align=\"right\"><font size=\"-1\">".$mokestis."</font></td>";
			$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\" align=\"right\"><font size=\"-1\">".$xsuma."</font></td>";
			$html .= "</tr>";
		}
		
		$visosupvm += $line["I07_SUMA"] + $line["I07_PVM"];
		if ($line["I07_MOKESTIS_P"] == 5) {
			$pvm_5 += $line["I07_PVM"];
		} else if ($line["I07_MOKESTIS_P"] == 9) {
			$pvm_9 += $line["I07_PVM"];
		} else if ($line["I07_MOKESTIS_P"] == 18) {
			$pvm_18 += $line["I07_PVM"];
		} else if ($line["I07_MOKESTIS_P"] == 19) {
			$pvm_19 += $line["I07_PVM"];
		} else if ($line["I07_MOKESTIS_P"] == 21) {
			$pvm_21 += $line["I07_PVM"];
		}
		
		
		$duom[] = array('code'=> $kodas, 'name'=> $pav , 'unit'=> $matas , 'qty'=> $kiekis , 'price'=>$kainabe, 'percent'=>$nuolaida,  'price2'=>$kainapo, 'tax'=>$mokestis, 'price3'=>$xsuma);
		
		
	}
	
	$myFile = "parasai/tekstas.txt";
	$fh = fopen($myFile, 'r');
	$tekstas = fread($fh, filesize($myFile));
	$tekstas = str_replace(b"\xEF\xBB\xBF","",$tekstas);
	fclose($fh);

	if (!empty($manager)) {
		$img = removeLtChars(iconv('windows-1257', 'UTF-8',trim($manager["I32_KODAS_MS"]))). ".jpg";
		if (!file_exists("parasai/".$img)){
			$img = "blank.jpg";
		}
		$man = iconv('windows-1257', 'UTF-8',trim($manager["N15_PAV"]));
		$par = iconv('windows-1257', 'UTF-8',trim($manager["N15_PAREIGOS"]));
		$isr = "Sąskaitą išrašė";
	} else {
		$img = "blank.jpg";
		$man = "";
		$par = "";
		$isr = "";
	}
//if (!isset($DEB_KRED_TIPAS) || $DEB_KRED_TIPAS != "1") {
			$nuolaida = 0;
			$nuolaidos_pvm = 0;
			$nuolaida_be_pvm = 0;
			if (isset($nuol) && !empty($nuol)) {

				if ($nuol['nuolaida'] < 0) {
					$nuol_txt = "Nuolaida degalams";
					$nuolaida = abs($nuol['nuolaida']);
					$nuolaidos_pvm = 0.1735537190082644628099173553719 * $nuolaida;
					$nuolaida_be_pvm = $nuolaida - $nuolaidos_pvm;					
				} else {
					$nuol_txt = "Kainos koregavimas";
					$nuolaida = ($nuol['nuolaida'])*(-1);
					$nuolaidos_pvm = 0.1735537190082644628099173553719 * $nuolaida;
					$nuolaida_be_pvm = $nuolaida - $nuolaidos_pvm;						
				}
			}
			if ($dd >= mktime(0,0,0,1,1,2015)) {			
				$zodziais = toLit($visosupvm-$nuolaida,"EUR");
			} else {
				$zodziais = toLit($visosupvm-$nuolaida,"LTL");
			}
			if (isset($_REQUEST["cred"]) && $_REQUEST["cred"] == "1") {
				$zodziais = "minus ".$zodziais;
			}
			$pvmtxt = "";
			$pvmsumtxt = "";
			if ($skipedsum != "0"){
				$pvmtxt = "Kelių vinjetės<br>";
				$pvmsumtxt = sprintf("%01.2f",$skipedsum*$zenklas)."<br>";
			}
			if ($pvm_5 > 0) {
				$pvmtxt .= "<br>PVM 5%";
				$pvmsumtxt .= "<br>" . sprintf("%01.2f",$pvm_5*$zenklas) ;
			} 
			if ($pvm_9 > 0) {
				$pvmtxt .= "<br>PVM 9%";
				$pvmsumtxt .=  "<br>" .sprintf("%01.2f",$pvm_9*$zenklas) ;
			} 
			if ($pvm_18 > 0) {
				$pvmtxt .= "<br>PVM 18%";
				$pvmsumtxt .=  "<br>" .sprintf("%01.2f",$pvm_18*$zenklas) ;
			} 
			if ($pvm_19 > 0) {
				$pvmtxt .= "<br>PVM 19%";
				$pvmsumtxt .=  "<br>" .sprintf("%01.2f",$pvm_19*$zenklas) ;
			} 
			if ($pvm_21 > 0) {
				$pvmtxt .= "<br>PVM 21%";
				$pvmsumtxt .=  "<br>" .sprintf("%01.2f",($pvm_21-$nuolaidos_pvm)*$zenklas) ;
			}
			
		if (isset($_REQUEST["type"]) && $_REQUEST["type"] == "p") {	
			if (isset($_REQUEST["cred"]) && $_REQUEST["cred"] == "1") {
				$colspan = 0;
			} else {
				$colspan = 2;
			}
		} else {
			$colspan = 0;
		}
		
		$text_eur = "";
		$sum_eur = "";
		
		if ($dd >= mktime(0,0,0,7,31,2014) && $dd <= mktime(23,59,59,12,31,2014)) {
			$text_eur = "Suma apmokėjimui EUR";
			$sum_eur = sprintf("%01.2f",($visosupvm-$nuolaida)*$zenklas*0.28962);
		} else if ($dd >= mktime(0,0,0,1,1,2015) && $dd <= mktime(23,59,59,8,31,2015)) {
			$text_eur = "Suma apmokėjimui LTL";
			$sum_eur = sprintf("%01.2f",($visosupvm-$nuolaida)*$zenklas*3.4528);		
		}
		
		if ($nuolaida != 0) {
			$nuolviso = sprintf("%01.2f",$nuolaida_be_pvm*(-1)*$zenklas);
			$html .= "<tr><td colspan=\"" . (4+$colspan) ."\"><font size=\"-1\"></font></td><td align=\"right\"><font size=\"-1\">".$nuol_txt."</font></td><td></td><td align=\"right\" ><font size=\"-1\">".$nuolviso."</font></td></tr>";
		/*	if ($delcol == 8) {
				$nuol_txt1 = $nuol_txt;
				$nuolviso1 = $nuolviso;
				$nuol_txt2 = "";
				$nuolviso2 = "";			
			} else {
				$nuol_txt2 = $nuol_txt;
				$nuolviso2 = $nuolviso;
				$nuol_txt1 = "";
				$nuolviso1 = "";			
			}*/
		} else {
		/*	$nuol_txt1 = "";
			$nuolviso1 = "";
			$nuol_txt2 = "";
			$nuolviso2 = "";	*/		
		}
			$totalwovat = sprintf("%01.2f",($visobepvm-$nuolaida_be_pvm)*$zenklas);
			
			$apmoksuma = sprintf("%01.2f",($visosupvm-$nuolaida)*$zenklas);			
		/*	if ($delcol == 8) {
				$txtwovat1 = "Viso be PVM";
				$totalwovat1 = $totalwovat;
				$txtwovat2 = "";
				$totalwovat2 = "";	
				$pvmtxt1 = $pvmtxt;
				$pvmsumtxt1 = $pvmsumtxt;
				$pvmtxt2 = "";
				$pvmsumtxt2 = "";	
				$apmoksumatxt1 = "Suma apmokėjimui";
				$apmoksuma1 = $apmoksuma;
				$apmoksumatxt2 = "";
				$apmoksuma2 = "";	
				$txt_eur1 = $text_eur;
				$sum_eur1 = $sum_eur;
				$txt_eur2 = "";
				$sum_eur2 = "";				
			} else {
				$txtwovat1 = "";
				$totalwovat1 = "";
				$txtwovat2 = "Viso be PVM";
				$totalwovat2 = $totalwovat;		
				$pvmtxt2 = $pvmtxt;
				$pvmsumtxt2 = $pvmsumtxt;
				$pvmtxt1 = "";
				$pvmsumtxt1 = "";	
				$apmoksumatxt2 = "Suma apmokėjimui";
				$apmoksuma2 = $apmoksuma;
				$apmoksumatxt1 = "";
				$apmoksuma1 = "";		
				$txt_eur2 = $text_eur;
				$sum_eur2 = $sum_eur;
				$txt_eur1 = "";
				$sum_eur1 = "";						
			} */
			
			
			
			$html .= "<tr><td colspan=\"" . (4+$colspan) ."\"></td><td align=\"right\"><font size=\"-1\">Viso be PVM</font></td><td></td><td align=\"right\" ><font size=\"-1\">".$totalwovat."</font></td></tr>";

			$html .= "<tr><td colspan=\"" . (2+$colspan) ."\"><font size=\"-1\">"."</font></td><td rowspan=\"2\" colspan=\"2\"></td>
			<td align=\"right\"><font size=\"-1\">".$pvmtxt."</font></td>
			<td></td><td align=\"right\"><font size=\"-1\">".$pvmsumtxt."</font></td></tr>";

			$html .= "<tr><td colspan=\"" . (3+$colspan) ."\"><font size=\"-1\"></font></td><td></td><td align=\"right\" style=\"border-top:1px solid #000000;\"><font size=\"-1\">Suma apmokėjimui</font></td><td colspan=\"2\" style=\"border-top:1px solid #000000;\" align=\"right\"><font size=\"-1\">".$apmoksuma."</font></td></tr>";
			$html .= "<tr><td colspan=\"" . (3+$colspan) ."\"><font size=\"-1\">Suma žodžiais</font></td><td></td><td align=\"right\" ><font size=\"-1\"><i>".$text_eur."</i></font></td><td colspan=\"2\" align=\"right\"><font size=\"-1\"><i>".$sum_eur."</i></font></td></tr>";
			$html .= "<tr><td colspan=\"" . (7+$colspan) ."\"><font size=\"-1\">". trim($zodziais) ."</font></td></tr>";	
			$html .= "<tr><td colspan=\"" . (7+$colspan) ."\"></td></tr>";
			$html .= "<tr><td colspan=\"" . (7+$colspan) ."\"><font size=\"-1\">".$isr."</font></td></tr>";
			$html .= "<tr><td colspan=\"" . (7+$colspan) ."\"><font size=\"-1\">".$par . " " .$man."</font></td></tr>";
			$html .= "<tr><td colspan=\"" . (7+$colspan) ."\"><img height=\"60\" src=\"parasai/".$img."\"/></td></tr>";	
			$html .= "</table><br><br>

	
	<font size=\"+2\">Dėkojame, kad naudojatės mūsų paslaugomis!</font><br><font size=\"-2\">
	". $tekstas . "</font>";

//	} else {
//		include("nest_nuolaida.php");
//	} 	
	
if (isset($_REQUEST['nopdf']) && $_REQUEST['nopdf'] =="1"){
	echo $html;
} else {

	if (isset($tfile)) {
		
		// Include classes
		include_once('inc/tbs_class.php'); // Load the TinyButStrong template engine
		include_once('inc/tbs_plugin_opentbs.php'); // Load the OpenTBS plugin		
		
		// prevent from a PHP configuration problem when using mktime() and date()
		if (version_compare(PHP_VERSION,'5.1.0')>=0) {
			if (ini_get('date.timezone')=='') {
				date_default_timezone_set('UTC');
			}
		}		
				
		// Initialize the TBS instance
		$TBS = new clsTinyButStrong; // new instance of TBS
		$TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN); // load the OpenTBS plugin		
		
		$TBS->LoadTemplate($tfile, OPENTBS_ALREADY_UTF8); // Also merge some [onload] automatic fields (depends of the type of document).

// $TBS->Plugin(OPENTBS_DEBUG_XML_CURRENT, true); // Display the intented XML of the current sub-file, and exit.
// $TBS->Plugin(OPENTBS_DEBUG_INFO, true); // Display information about the document, and exit.
// $TBS->Plugin(OPENTBS_DEBUG_XML_SHOW); // Tells TBS to display information when the document is merged. No exit.
		
		$logo = "logo.jpg";
		$company = preg_replace("/<.*?>/", " ", $company);
		$mcompany = preg_replace("/<.*?>/", " ", $mcompany);
		$address = preg_replace("/<.*?>/", " ", $address);
		$maddress = preg_replace("/<.*?>/", " ", $maddress);
		$imcode = $ourinfo["N08_IM_KODAS"];
		$vatcode = $ourinfo["N08_PVM_KODAS"];
		$bankcode = $saskinfo["N33_KODAS_WS"];
		$iban = $saskinfo["N33_S_KODAS"];
		$mimcode = $minfo["N08_IM_KODAS"];
		$mvatcode = $minfo["N08_PVM_KODAS"];
		$title = $title." Serija ".substr($_REQUEST["dok_nr"],0,3)." Nr.".substr($_REQUEST["dok_nr"],3);
		/*$titkaina = preg_replace("/<.*?>/", " ", $titkaina);*/
		if (isset($pastabos)) $pastabos = "";
		/*$titproc = preg_replace("/<.*?>/", " ", $titproc);
		$titkaina2 = preg_replace("/<.*?>/", " ", $titkaina2);*/
		$tekstas = preg_replace("/<.*?>/", " ", $tekstas);
		
		$pvmtxt = preg_replace("/<.*?>/", " ", $pvmtxt);
		$pvmsumtxt = preg_replace("/<.*?>/", " ", $pvmsumtxt);
		/*$pvmtxt2 = preg_replace("/<.*?>/", " ", $pvmtxt2);*/
		/*$pvmsumtxt2 = preg_replace("/<.*?>/", " ", $pvmsumtxt2);*/
		
	
		$TBS->PlugIn(OPENTBS_CHANGE_PICTURE, "logo", $logo);
		$TBS->PlugIn(OPENTBS_CHANGE_PICTURE, "parasas", "parasai/".$img);
		
	
		$TBS->MergeBlock('a', $duom);
	
		header('Content-Description: File Transfer');
		header('Content-Type: application/msword');
		header('Content-Disposition: attachment; filename="'.trim($rimone["n08_c_invoice"]).'"');
		header('Content-Transfer-Encoding: binary');
		
		// Output the result as a downloadable file (only streaming, no data saved in the server)
		$TBS->Show(OPENTBS_DOWNLOAD + OPENTBS_NOHEADER, trim($rimone["n08_c_invoice"])); // Also merges all [onshow] automatic fields.
		// Be sure that no more output is done, otherwise the download file is corrupted with extra data.
		exit();
		
	} else {

	require_once('tcpdf/config/lang/eng.php');
	require_once('tcpdf/tcpdf.php');

	// Extend the TCPDF class to create custom Header and Footer
	class MYPDF extends TCPDF {

		private $hd = "header";
		
		public function setHeaderString($value){
			$this->hd = $value;
		}
		
		//Page header
		public function Header() {        
			$this->writeHTML($this->hd, true, false, true, false, '');
		}
	}
	
		// create new PDF document
		$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		// set document information
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Darius Mikėnas');
		$pdf->SetTitle('Saskaita apmokejimui');
		$pdf->SetSubject('Saskaita');
		$pdf->SetKeywords('Saskaita');

		// set default header data
		$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
		$pdf->setHeaderString($header);
		$pdf->setPrintHeader(false);
		$pdf->setPrintFooter(false);

		// set default monospaced font
		$pdf->SetDefaultMonospacedFont('freesans');

		//set margins
		$pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

		//set auto page breaks
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

		//set image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		//set some language-dependent strings
		$pdf->setLanguageArray($l);

		// ---------------------------------------------------------

		// set font
		//$pdf->AddFont('freesans', 'B', 8);
		$pdf->SetFont('freesans', '', 8);
		$pdf->setHeaderFont(Array('freesans', '', 8));

		$pdf->setJPEGQuality(75);
		
		// add a page
		$pdf->AddPage();



		$pdf->writeHTML($html, true, false, true, false, '');
		//Close and output PDF document
		$pdf->Output('saskaita.pdf', 'D');
	}
}

?>